<?php

namespace App\Http\Controllers\Service;

use Illuminate\Http\Request;

use App\Http\Requests;

//引入外部自定义的类
use App\Tool\Validate\ValidateCode;
use App\Tool\SMS\SendTemplateSMS;
use App\Entity\TempPhone;
use App\Models\M3Result;

class ValidateCodeController extends CommonController
{
    //生成图形验证码的方法
    public function create(Request $request)
    {
        $validate = new ValidateCode();
        //将验证码存入到session里面
        $request->session()->put('validate_code',$validate->getCode());
        return $validate->doimg();
    }

    //发送手机短信6位数验证码
    public function sendSMS(Request $request)
    {
        $m3_result = new M3Result();

        $phone = $request->input('phone', '');
        if ($phone == '') {
            $m3_result->status = 1;
            $m3_result->message = '手机号不能为空';
            return $m3_result->toJson();
        }

        $sendTemplateSMS = new SendTemplateSMS();

        $charset = '1234567890';
        $code = '';
        $_len = strlen($charset) - 1;
        for ($i = 0; $i < 6; ++$i) {
            $code .= $charset[mt_rand(0, $_len)];
        }

        //指定发送到的手机号，轮循的验证码为1234567890，有效时间为60分钟，模板为第一个模板（默认的模板）
        $m3_result = $sendTemplateSMS->sendTemplateSMS($phone, array($code, 60), 1);
        if ($m3_result->status == 0) { //如果短信发送成功
            //将数据信息存入到数据库中的数据表中
            $tempPhone = TempPhone::where('phone', $phone)->first();
            if ($tempPhone == null) {
                $tempPhone = new TempPhone();
            }
            $tempPhone->phone = $phone;
            $tempPhone->code = $code;
            $tempPhone->deadline = date('Y-m-d H-i-s', time() + 60 * 60);
            $tempPhone->save();

        }
        return $m3_result->toJson();
    }
}
